from httpx import Response
from httpx._exceptions import (
    TimeoutException,
    NetworkError,
    ProxyError
)

from utils.proxy import ProxyPool
from utils import logger
from items import RequestItem, ResponseItem


class Base:
    retry_times = 10
    retry_exception = (TimeoutException, NetworkError, ProxyError)

    def get_proxy(self, request_item: RequestItem) -> str:
        """
        根据传入的参数获取初始化的代理IP
        :param request_item: RequestItem
        :return: proxy
        """
        proxy = None
        if isinstance(request_item.proxies, bool):
            if request_item.proxies:
                proxy = ProxyPool.get_one()
        elif isinstance(request_item.proxies, str):
            proxy = request_item.proxies

        return proxy

    def success_response(self, request_item: RequestItem, resp: Response) -> ResponseItem:
        """
        处理成功的响应
        :param request_item:
        :param resp:
        :return:
        """
        return ResponseItem(
            url=resp.url.__str__(),
            status_code=resp.status_code,
            content=list(resp.content),
            headers=resp.headers,
            cookies={k: v for k, v in resp.cookies.items()},
            request_item=request_item
        )

    def error_response(self, request_item, errors):
        """
        处理报错响应
        :param request_item:
        :param errors:
        :return:
        """
        logger.exception(request_item.json())
        return ResponseItem(
            url=request_item.url,
            errors=errors,
            request_item=request_item
        )
